<script setup>
import { reactive, ref, onMounted, nextTick } from 'vue'
import { myConfrim } from '@/utils'
import { getAssignClassApi } from '@/api/classes'
import { getRoomByStoreyIdApi, assignSaveBedApi, getAssignBedListApi, deleteAssignApi } from '@/api/setAssign'
import { getBuildListBySexApi, getStoryListApi } from '@/api/build'
import { cleanBedApi } from '@/api/setAssign'

// 弹窗属性
const assignDialog = reactive({
    title: '',
    height: 300,
    width: 830,
    visible: false
})
const parms = reactive({
    // 楼栋id
    buildId: '',
    // 层数id
    storeyId: ''
})
// 侧边栏高度
const assideHeight = ref(0)
// 是否改变
const isChange = ref(0)
// 班级列表
const classList = ref([])
// 楼栋列表
const buildList = ref([])
// 层数列表
const storyList = ref([])
// 宿舍列表
const roomList = ref([])
// 表格高度
const tableHeight = ref(0)
// 表格数据
const tableData = ref([])
// 搜索区域绑定
const searchModel = reactive({
    currentPage: 1,
    pageSize: 5,
    className: '',
    classYear: '',
    total: 0
})
const bed = reactive({
    classId: '',
    className: '',
    sex: '',
    girlCount: 0,
    manCount: 0,
    total: 0
})

const treeProps = {
    children: 'children',
    label: 'roomCode'
}

onMounted(() => {
    assideHeight.value = window.innerHeight - 200
    tableHeight.value = window.innerHeight - 200
})

// 获取班级列表
const getAssignClass = async () => {
    // 先清空上一次的宿舍数据
    tableData.value = []
    let res = await getAssignClassApi(searchModel)
    if (res) {
        classList.value = res.data.records
        searchModel.total = res.data.total
        nextTick(() => {
            document.querySelector('#class0')?.click()
        })
    }
}
getAssignClass()

// 根据班级id获取对应的宿舍
const getAssignBedList = async (classId) => {
    console.log(classId)
    let res = await getAssignBedListApi({
        classId: classId
    })
    if (res) {
        tableData.value = res.data
    }
}
// 搜索按钮
const searchBtn = () => {
    // 获取班级对应的宿舍信息
    getAssignClass()
}
// 重置按钮
const closeBtn = () => {
    searchModel.className = ''
    searchModel.classYear = ''
    getAssignClass()
}
// 分配宿舍按钮
const assignBtn = async (val) => {
    // 清空上一次的楼栋信息
    parms.buildId = ''
    buildList.value = []
    parms.storeyId = ''
    storyList.value = []
    roomList.value = []
    // 获取楼栋列表
    let res = await getBuildListBySexApi({
        type: val
    })
    if (res) {
        buildList.value = res.data
    }
    bed.sex = val === '0' ? '男生' : '女生'
    bed.total = val === '0' ? bed.manCount : bed.girlCount
    assignDialog.title = `为 [ ${bed.className} ] 分配 [ ${bed.sex} ] 宿舍,需要 [ ${bed.total} ] 个床位`
    assignDialog.visible = true
}
// 左侧班级点击事件
const itemClick = (item, index) => {
    isChange.value = index
    bed.classId = item.classId
    bed.className = item.className
    bed.girlCount = item.girlCount
    bed.manCount = item.manCount
    // 获取班级对应的宿舍信息
    getAssignBedList(bed.classId)
}
// 页大小改变事件
const sizeChange = (size) => {
    searchModel.pageSize = size
    getAssignClass()
}

const currentChange = (page) => {
    searchModel.currentPage = page
    getAssignClass()
}
const assignTree = ref(null)
// 弹窗确认(分配宿舍)事件
const onConfirm = async () => {
    // 判断是否选择班级
    if (!bed.classId) {
        ElMessage({
            message: '请选择班级',
            type: 'warning',
        })
        return
    }
    // 获取当前选择的节点数据
    let ids = assignTree.value.getCheckedNodes()
    if (ids.length === 0) {
        ElMessage({
            message: '请选择宿舍',
            type: 'warning',
        })
        return
    }
    // 组装数据
    const list = ids.map(item => {
        if (item.type === '0') {
            return {
                bedId: item.roomId,
                classId: bed.classId
            }
        } else {
            return false
        }

    }).filter(Boolean)
    // 保存
    let res = await assignSaveBedApi(list)
    if (res) {
        ElMessage({
            message: res.msg,
            type: 'success',
        })
        // 刷新班级宿舍信息
        getAssignBedList(bed.classId)
        assignDialog.visible = false
    }
}
// 弹窗取消事件
const onClose = () => assignDialog.visible = false
// 楼栋选择事件
const selectBuildChange = async (val) => {
    // 清空层数信息
    parms.storeyId = ''
    storyList.value = []
    // 查询楼栋的层数
    let res = await getStoryListApi({
        buildId: val
    })
    if (res) {
        storyList.value = res.data
    }
}
// 选择层数改变事件
const selectStorey = async (val) => {
    let res = await getRoomByStoreyIdApi({
        storeyId: val
    })
    if (res) {
        roomList.value = res.data
    }
}
// 删除床位
const childDelete = async (row) => {
    let confirm = await myConfrim('确定要删除该宿舍吗?')
    if (confirm) {
        let parm = {
            bedId: row.bedId,
            classId: bed.classId
        }
        let res = await deleteAssignApi(parm)
        if (res) {
            ElMessage({
                message: res.msg,
                type: 'success',
            })
            // 刷新班级宿舍信息
            getAssignBedList(bed.classId)
        }
    }
}
const cleanBtn = async () => {
    if (!bed.classId) {
        ElMessage({
            message: '请选择要清空宿舍的班级',
            type: 'warning',
        })
        return
    }
    const confirm = await myConfrim(`确定要清空 [ ${bed.className} ] 的宿舍吗?`)
    if (confirm) {
        let res = await cleanBedApi({
            classId: bed.classId
        })
        if (res) {
            ElMessage({
                message: res.msg,
                type: 'success',
            })
            getAssignBedList(bed.classId)
        }
    }
}
</script>

<template>
    <el-container>
        <el-header class="header">
            <!-- 搜索 -->
            <el-form :model="searchModel" :inline="true">
                <el-form-item>
                    <el-date-picker style="width: 100%;" v-model="searchModel.classYear" placeholder="选择年份" type="year"
                        value-format="YYYY">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="searchModel.className" placeholder="请输入班级"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button icon="Search" @click="searchBtn">搜索</el-button>
                    <el-button style="color: #ff7670;" icon="Close" @click="closeBtn">重置</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button icon="Plus" type="primary" @click="assignBtn('0')">分配男生宿舍</el-button>
                    <el-button icon="Plus" type="success" @click="assignBtn('1')">分配女生宿舍</el-button>
                    <el-button icon="Delete" type="danger" @click="cleanBtn">清空宿舍</el-button>
                </el-form-item>
            </el-form>
        </el-header>
        <el-container>
            <!-- 左侧菜单 -->
            <el-aside class="leftside" width="230px">
                <div class="item-container" :style="{ height: assideHeight + 'px' }">
                    <div :id="'class' + index" v-for="(item, index) in classList" :key="index" class="side-item"
                        @click="itemClick(item, index)" :class="{ isActive: isChange === index }">
                        <div class="item-left">
                            <div class="class-title">
                                {{ item.className }}
                                <span style="margin-left: 10px;">(总共: {{ item.stuCount }}人)</span>
                            </div>
                            <div class="class-sex">
                                <div class="man">男:{{ item.manCount }}</div>
                                <div class="girl">女:{{ item.girlCount }}</div>
                            </div>
                        </div>
                        <i class="el-icon-arrow-right item-right"></i>
                    </div>
                </div>
                <el-pagination class="pages" @size-change="sizeChange" @current-change="currentChange"
                    :current-page.sync="searchModel.currentChange" :page-sizes="[5, 10, 15]"
                    :page-size="searchModel.pageSize" layout="prev, next" prev-text="上一页" next-text="下一页"
                    :total="searchModel.total" small>
                </el-pagination>
            </el-aside>
            <el-main>
                <!-- 宿舍信息 -->
                <el-table :height="tableHeight" :data="tableData" border stripe>
                    <el-table-column width="100" type="expand">
                        <template #default="scope">
                            <el-table border :data="scope.row.children">
                                <el-table-column label="床位编号" prop="bedCode"></el-table-column>
                                <el-table-column label="操作" align="center" width="180">
                                    <template #default="scopeSub">
                                        <el-button round type="danger" icon="Delete"
                                            @click="childDelete(scopeSub.row)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </template>
                    </el-table-column>
                    <el-table-column label="宿舍编号" prop="roomCode"></el-table-column>
                    <el-table-column align="center" label="宿舍类型">
                        <template #default="scope">
                            <el-tag v-if="scope.row.roomType === '1'">1人间</el-tag>
                            <el-tag v-if="scope.row.roomType === '2'">2人间</el-tag>
                            <el-tag v-if="scope.row.roomType === '4'">4人间</el-tag>
                            <el-tag v-if="scope.row.roomType === '6'">6人间</el-tag>
                            <el-tag v-if="scope.row.roomType === '8'">8人间</el-tag>
                        </template>
                    </el-table-column>
                </el-table>
            </el-main>
        </el-container>

        <!-- 弹窗 -->
        <el-dialog v-model="assignDialog.visible" :width="assignDialog.width" :close-on-click-modal="false">
            <template #header>
                <h1>{{ assignDialog.title }}</h1>
            </template>
            <div :style="{ height: assignDialog.height + 'px' }">
                <el-container style="height: 300px;">
                    <el-header style="border-bottom: 1px solid #dcdfe6; height: 40px;">
                        <el-form :inline="true">
                            <el-form-item label="楼栋">
                                <el-select @change="selectBuildChange" v-model="parms.buildId" style="width: 100%;"
                                    placeholder="请选择楼栋">
                                    <el-option v-for="(item, index) in buildList" :label="item.buildName"
                                        :value="item.buildId" :key="index">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="楼层">
                                <el-select @change="selectStorey" v-model="parms.storeyId" style="width: 100%;"
                                    placeholder="请选择楼层">
                                    <el-option v-for="(item, index) in storyList" :label="item.storeyName"
                                        :value="item.storeyId" :key="index">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-button icon="Search">查询</el-button>
                                <el-button style="color: #ff7670;" icon="Close">取消</el-button>
                            </el-form-item>
                        </el-form>
                    </el-header>
                    <el-main>
                        <el-tree ref="assignTree" :data="roomList" default-expand-all show-checkbox node-key="roomId"
                            :props="treeProps">
                        </el-tree>
                    </el-main>
                </el-container>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onClose">取消</el-button>
                    <el-button type="primary" @click="onConfirm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </el-container>
</template>

<style scoped>
.header {
    border-bottom: 1px solid #dcdfe6;
    display: flex;
    align-items: center;
}

.item-container {
    display: flex;
    flex-direction: column;
}

.leftside {
    border-right: 1px solid #dcdfe6;
    border-bottom: 1px solid #dcdfe6;
    display: flex;
    flex-direction: column;
}

.leftside .side-item {
    display: flex;
    height: 55px;
    border-bottom: 1px solid #dcdfe6;
    align-items: center;
    cursor: pointer;
}

.leftside .side-item .item-left {
    padding-left: 10px;
    flex-grow: 1;
}

.leftside .side-item .item-left .class-title {
    color: #686868;
    font-size: 13px;
}

.leftside .side-item .item-left .class-sex {
    display: flex;
    color: #999;
    font-size: 12px;
    padding-top: 8px;
}

.leftside .side-item .item-left .class-sex .man {
    flex-grow: 1;
}

.leftside .side-item .item-left .class-sex .girl {
    flex-grow: 1;
}

.leftside .side-item .item-right {
    padding-right: 10px;
    color: #b2b2b2;
}

.pages {
    text-align: center;
}

.isActive {
    background: #f8f8f8;
}
</style>